<?php

namespace App\Console\Commands\Pay;


use App\Enums\Common\NsqEnum;
use App\Service\Pay\MybankService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Kuafu\Nsq\NsqSubscriber;
use NSQClient\Contract\Message;

class NsqSubMybankRegister extends Command
{
    protected $signature = 'nsq:sub-mybank-register';

    protected $description = 'NSQ订阅网商银行用户注册激活';

    private array $data;

    const STATUS_1 = 1; // 申请中
    const STATUS_2 = 2; // 激活中
    const STATUS_3 = 3; // 已激活

    // 用户注册结果
    const PRE_REGISTER_STATUS_0 = 0;
    const PRE_REGISTER_STATUS_1 = 1; // 成功
    const PRE_REGISTER_STATUS_2 = 2; // 失败

    // 用户在网商手动激活结果
    const REGISTER_STATUS_0 = 0;
    const REGISTER_STATUS_1 = 1; // 成功
    const REGISTER_STATUS_2 = 2; // 失败

    public function handle()
    {
        (new NsqSubscriber(config('nsq.default.address')))
            ->sub(NsqEnum::TOPIC_RMS_MYBANK_REGISTER, NsqEnum::CHANNEL_TIGER_SUB_MYBANK_REGISTER,
                function (Message $message) {

                    Log::info('sub-mybank-register:', $message->data());

                    // debug
                    if (isTest()) {
                        dump($message->data());
                    }

                    $data = $message->data();

                    // 尝试在这用dispatch，不知道为啥就是不生效。只能先用sleep了
                    sleep(3);

                    try {
                        $this->doHandle($data);
                    } catch (\Exception $e) {
                        \ExceptionNotifier::report($e);
                    }

                    $message->done();
                });
    }

    private function doHandle(array $data)
    {
        Log::info("NsqSubMybankRegisterx 1", $data);

        $status                = $data['entry']['status'] ?? 0;
        $userId                = $data['entry']['userId'] ?? 0;
        $outOrderNo            = $data['entry']['outOrderNo'] ?? '';
        $preRegisterStatus     = (int)($data['entry']['preRegisterStatus'] ?? 0);
        $preRegisterFailReason = $data['entry']['preRegisterFailReason'] ?? '';
        $registerStatus        = (int)($data['entry']['registerStatus'] ?? 0);
        $registerFailReason    = $data['entry']['registerFailReason'] ?? 0;

        if (!$outOrderNo || !$userId) {
            return;
        }

        $finish = null;

        if ($status == self::STATUS_2) {

            // 用户注册
            $finish = (new MybankService($userId))->mybankAudit($outOrderNo, $preRegisterStatus,
                $preRegisterFailReason);
        } elseif ($status == self::STATUS_3) {

            // 网商激活
            $finish = (new MybankService($userId))->finish($outOrderNo, $registerStatus, $registerFailReason);
        }

        Log::info("NsqSubMybankRegister finish:{$finish}",
            ['userId' => $userId, 'outOrderNo' => $outOrderNo, 'status' => $status]);
    }
}
